//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Log.SiteLog;
namespace DotNetNuke.Modules.Admin.SiteLog
{
	partial class SiteLog : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		private void BindData()
		{
			string strPortalAlias;
			strPortalAlias = Common.Globals.GetPortalDomainName(PortalAlias.HTTPAlias, Request, false);
			if (strPortalAlias.IndexOf("/") != -1) {
				strPortalAlias = strPortalAlias.Substring(0, strPortalAlias.LastIndexOf("/") - 1);
			}
			string strStartDate = txtStartDate.Text;
			System.DateTime dtStart = System.DateTime.Parse(strStartDate);
			if (!String.IsNullOrEmpty(strStartDate)) {
				strStartDate = strStartDate + " 00:00";
			}
			string strEndDate = txtEndDate.Text;
			System.DateTime dtEnd = System.DateTime.Parse(strEndDate);
			if (!String.IsNullOrEmpty(strEndDate)) {
				strEndDate = strEndDate + " 23:59";
			}
			UserController objUsers = new UserController();
			ArrayList arrUsers;
			DataTable dt = new DataTable();
			DataView dv;
			switch (cboReportType.SelectedItem.Value) {
				case "10":
					arrUsers = UserController.GetUsers(PortalId);
					dt = new DataTable();
					dt.Columns.Add(new DataColumn("Full Name", typeof(string)));
					dt.Columns.Add(new DataColumn("User Name", typeof(string)));
					dt.Columns.Add(new DataColumn("Date Registered", typeof(System.DateTime)));
					foreach (UserInfo objUser in arrUsers) {
						if (objUser.Membership.CreatedDate >= dtStart && objUser.Membership.CreatedDate <= dtEnd && objUser.IsSuperUser == false) {
							DataRow dr = dt.NewRow();
							dr["Date Registered"] = objUser.Membership.CreatedDate;
							dr["Full Name"] = objUser.Profile.FullName;
							dr["User Name"] = objUser.Username;
							dt.Rows.Add(dr);
						}
					}

					dv = new DataView(dt);
					dv.Sort = "Date Registered DESC";
					grdLog.DataSource = dv;
					grdLog.DataBind();
					break;
				case "11":
					arrUsers = UserController.GetUsers(PortalId);
					dt = new DataTable();
					dt.Columns.Add(new DataColumn("Full Name", typeof(string)));
					dt.Columns.Add(new DataColumn("User Name", typeof(string)));
					dt.Columns.Add(new DataColumn("Country", typeof(string)));
					foreach (UserInfo objUser in arrUsers) {
						if (objUser.Membership.CreatedDate >= dtStart && objUser.Membership.CreatedDate <= dtEnd && objUser.IsSuperUser == false) {
							DataRow dr = dt.NewRow();
							dr["Country"] = objUser.Profile.Country;
							dr["Full Name"] = objUser.Profile.FullName;
							dr["User Name"] = objUser.Username;
							dt.Rows.Add(dr);
						}
					}

					dv = new DataView(dt);
					dv.Sort = "Country";
					grdLog.DataSource = dv;
					grdLog.DataBind();
					break;
				default:
					SiteLogController objSiteLog = new SiteLogController();
					IDataReader reader = objSiteLog.GetSiteLog(PortalId, strPortalAlias, Convert.ToInt32(cboReportType.SelectedItem.Value), Convert.ToDateTime(strStartDate), Convert.ToDateTime(strEndDate));
					grdLog.DataSource = reader;
					grdLog.DataBind();
					reader.Close();
					break;
			}
			if (grdLog.Items.Count > 0) {
				lblMessage.Visible = false;
				grdLog.Visible = true;
			} else {
				lblMessage.Visible = true;
				grdLog.Visible = false;
			}
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cmdCancel.Click += new EventHandler(cmdCancel_Click);
			cmdDisplay.Click += new EventHandler(cmdDisplay_Click);

			try {
				cmdStartCalendar.NavigateUrl = Common.Utilities.Calendar.InvokePopupCal(txtStartDate);
				cmdEndCalendar.NavigateUrl = Common.Utilities.Calendar.InvokePopupCal(txtEndDate);
				if (Page.IsPostBack == false) {
					string strSiteLogStorage = "D";
					if (!string.IsNullOrEmpty(Host.SiteLogStorage)) {
						strSiteLogStorage = Host.SiteLogStorage;
					}
					if (strSiteLogStorage == "F") {
						UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("FileSystem", this.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
						cmdDisplay.Visible = false;
					} else {
						switch (PortalSettings.SiteLogHistory) {
							case -1:
								break;
							case 0:
								UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("LogDisabled", this.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
								break;
							default:
								UI.Skins.Skin.AddModuleMessage(this, string.Format(Services.Localization.Localization.GetString("LogHistory", this.LocalResourceFile), PortalSettings.SiteLogHistory.ToString()), UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
								break;
						}
						cmdDisplay.Visible = true;
					}
					Common.Lists.ListController ctlList = new Common.Lists.ListController();
					Common.Lists.ListEntryInfoCollection colSiteLogReports = ctlList.GetListEntryInfoCollection("Site Log Reports");
					cboReportType.DataSource = colSiteLogReports;
					cboReportType.DataBind();
					cboReportType.SelectedIndex = 0;
					txtStartDate.Text = DateTime.Today.AddDays(-6).ToShortDateString();
					txtEndDate.Text = DateTime.Today.AddDays(1).ToShortDateString();
					if (Request.UrlReferrer != null) {
						if (Request.UrlReferrer.AbsoluteUri == Request.Url.AbsoluteUri) {
							ViewState["UrlReferrer"] = "";
						} else {
							ViewState["UrlReferrer"] = Convert.ToString(Request.UrlReferrer);
						}
					} else {
						ViewState["UrlReferrer"] = "";
					}
				}
				if (ViewState["UrlReferrer"] == null
					|| String.IsNullOrEmpty(ViewState["UrlReferrer"].ToString()))
				{
					cmdCancel.Visible = false;
				} else {
					cmdCancel.Visible = true;
				}
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdCancel_Click(object sender, System.EventArgs e)
		{
			try {
				Response.Redirect(Convert.ToString(ViewState["UrlReferrer"]));
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdDisplay_Click(object sender, System.EventArgs e)
		{
			try {
				BindData();
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
        /// <summary>
        /// ensure sitelog grid data is htmlencoded
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks></remarks>
        protected void grdLog_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            DataGridItem item = e.Item;
            ListItemType itemType = item.ItemType;
            if (((itemType == ListItemType.AlternatingItem) || (itemType == ListItemType.Item)))
            {
                TableCellCollection cells = item.Cells;
                foreach (TableCell cell in cells)
                {
                    cell.Text = HttpUtility.HtmlEncode(cell.Text.ToString());
                }
            }
        }

	}
}
